#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

>$OUTFILE

# mega-awk (Klimentev)
function create_sql() {
    #country=$1
    server=$1
    nawk '{if($4=="Mon")DoW=2;
	  if($4=="Tue")DoW=3;
	  if($4=="Wed")DoW=4;
	  if($4=="Thu")DoW=5;
	  if($4=="Fri")DoW=6;
	  if($4=="Sat")DoW=7;
	  if($4=="Sun")DoW=1;
	  printf "exec merge_conn_logg('\'$server\'','\'%s\'','\'%s\'','\'%s\'',to_date(\'\'%d' '%s' ",$1,$2,$3,DoW,$5;
	  if ($6<=9) {printf"0%s",$6} else {printf"%s",$6};
	  printf " %s'\'','\''D MON DD HH24:MI'\''),to_date(\'\'%d' '%s' ",$7,DoW,$5;    	  
	  if ($6<=9) {printf"0%s",$6} else {printf"%s",$6};
	  printf " %s'\'','\''D MON DD HH24:MI'\'')+to_dsinterval('\''",$7;    	  
	  if($10=="in")
	    {printf "999999999 00:00:00"}
	  else{
	   if($10~/\+/)
	    {printf "%s %s:00",substr($10,2,index($10,"+")-2),substr($10,index($10,"+")+1,length($10)-1-index($10,"+"))}
	   else
	    {printf "0 %s:00",substr($10,2,length($10)-2)}
	  };	  	    
	  printf "'\''));\n"
	  }'
}

#allow_hosts, not load
HostList1=$($ORACLE_HOME/bin/sqlplus  -s /NOLOG << END
connect $CONNECT_ARS
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET PAGESIZE 0
SET HEADING OFF
SET FEEDBACK OFF
select host from allow_hosts;
exit;
END )
exit_code=$?
[ "$exit_code" -ne 0 ] && { echo "$HostList1" | sed s/\*// >&2; exit $exit_code; }
HostList2=`echo "$HostList1" | sed s/^/^/ | sed s/$/$/ | sed 's/\*.*$//'` 
HostList=`echo $HostList2 | sed s/\ /\|/g`

#allow_users, not load
UserList1=$($ORACLE_HOME/bin/sqlplus  -s /NOLOG << END
connect $CONNECT_ARS
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET PAGESIZE 0
SET HEADING OFF
SET FEEDBACK OFF
select user_name from allow_accounts where acc_type='OS';
exit;
END )
exit_code=$?
[ "$exit_code" -ne 0 ] && { echo "$UserList1" | sed s/\*// >&2; exit $exit_code; }
UserList2=`echo "$UserList1" | sed s/^/^/ | sed s/$/$/` 
UserList=`echo $UserList2 | sed s/\ /\|/g`

count_days=3

INF "load data from servers ..."
ssh_command="last | nawk 'BEGIN {n=0}
			  \$2!~/^(ftp|console)$/ {
			     if (\$4!=day) {day=\$4; n=n+1};
                             if (n>$count_days) exit;
			     if (\$1!~/$UserList/ && \$3!~/$HostList/) print
			  }'"

srvlist=`get_hosts --os=Unix --control=YES`
INF "count hosts: `echo $srvlist | wc -w`"

    for server in $srvlist
    do
        (
	mkdir -p $TEMPDIR/data
	result=""
	SSH $user@$server "$ssh_command" result
	echo "$result" >> $TEMPDIR/data/$server
	) &
    done

wait

INF "create sql-commands ..."
cd $TEMPDIR/data
    for server in *
    do
	cat $server | grep -v ^$ | grep -v "wtmp begins" | create_sql $server >> $OUTFILE    
    done

INF "`cat $OUTFILE | wc -l | awk '{print $1}'` rows create"
echo "commit;" >> $OUTFILE
echo "exit;" >> $OUTFILE

INF "load in DB ..."
$ORACLE_HOME/bin/sqlplus > /dev/null -s $CONNECT_ARS @$OUTFILE

exit 0
